package cn.tedu.store.controller;

import cn.tedu.store.entity.Address;
import cn.tedu.store.entity.UserEntity;
import cn.tedu.store.service.IAddressService;
import cn.tedu.store.util.JsonResult;
import cn.tedu.store.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addresses")
public class AddressController {

    @Autowired
    IAddressService service;

    @Autowired
    RedisUtil redisUtil;

    @PostMapping("/{aid}/delete")
    public JsonResult<Void> removeAddress(HttpServletResponse resp, Integer aid, HttpSession session,Integer uid,String username){
//        UserEntity user=(UserEntity)session.getAttribute("user");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        service.removeAddress(aid,uid,username);
        return JsonResult.getSuccessJR();
    }

    @RequestMapping("/{aid}/set_default")
    public JsonResult<Void> setDefault(HttpServletResponse resp,Integer uid,String username,
            @PathVariable("aid") Integer aid, HttpSession session){
        resp.setHeader("Access-Control-Allow-Origin", "*");

        service.setDefault(aid,uid,username);
        return JsonResult.getSuccessJR();
    }

    @RequestMapping("/list")
    public JsonResult<List<Address>> findByUid( HttpServletResponse resp,Integer uid){
//        public JsonResult<List<Address>> findByUid(@CookieValue(value="EM_TICKET",required=false) String ticket, HttpServletResponse resp,Integer uid){
        resp.setHeader("Access-Control-Allow-Origin", "*");
//        UserEntity user=redisUtil.getUserInfo(ticket);
        List<Address> list=service.findByUid(uid);
        System.out.println(uid);
//        System.out.println(list);
        return JsonResult.getSuccessJR(list);
    }

    @PostMapping("/createAddress")
    public JsonResult<Void> createAddress(HttpServletResponse resp,Integer uid,String username,Address address, HttpSession session){
        resp.setHeader("Access-Control-Allow-Origin", "*");
//        UserEntity user=(UserEntity)session.getAttribute("user");
        service.createAddress(uid,username,address);
        return JsonResult.getSuccessJR();
    }

    /**
     * order-serivce服务远程访问
     * @param aid
     * @return
     */
    @PostMapping("/findByAid")
    public JsonResult<Address> findByAid(Integer aid,HttpServletResponse resp) {

        resp.setHeader("Access-Control-Allow-Origin", "*");
        return JsonResult.getSuccessJR(service.findByAid(aid));
    }
}
